//
//  MainViewController.swift
//  MQLWeibo
//
//  Created by MQL-IT on 2016/10/23.
//  Copyright © 2016年 MQL-IT. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpChildControllers()
        if childViewControllers.count > 4 {
            setUpComposeButton()
        }
    }
    
    
    /**
     protrait: 竖屏
     andscape: 横屏
     
     - 使用代码控制设备方向的好处,可以在需要横屏的时候单独处理
     - 设置支持的方向之后,当前的控制器及其子控制器都会遵循这个设置
     - 如果播放视频,通常都是通过modal展示的
    */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    //MARK: - 监听按钮的点击方法
    //FIXME: 没有实现
    //fileprivate:能保证方法私有,仅在本文件中可以访问;  private(私有级别更高)只能在一个{}内访问
    //@objc,在运行时,以消息发送的机制调用方法
    @objc fileprivate func composeStatus() {
        print("撰写微博")
    }
    //MARK: - 私有控件,撰写按钮
    lazy var composeButton: UIButton = UIButton(type: .custom)

}

//extension,类似于 OC 中的分类,在Swift中还可以用来切分代码块
//可以把相近功能的函数放在同一个 extension 中
//注意:和 OC 的分类一样, extension中不能定义属性
//MARK: - 设置界面
extension MainViewController {
    //设置撰写按钮
    fileprivate func setUpComposeButton() {
        tabBar.addSubview(composeButton)
        
        composeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        composeButton.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted")?.withRenderingMode(.alwaysOriginal), for: .normal)
        let count = CGFloat(childViewControllers.count)
        //将向内缩进的宽度减少,能够让按钮的宽度变大,盖住容错点,防止穿帮;
        let w = tabBar.bounds.width / count - 1
        //CGRectInset
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        //按钮监听方法
        
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
        
    }
    //设置所有子控制器  Call can throw, but it is not marked with 'try' and the error is not handled
    fileprivate func setUpChildControllers() -> () {
        
        let docdir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docdir as NSString).appendingPathComponent("main.json")
        //加载data
        var data = NSData(contentsOfFile: jsonPath)
        if data == nil {
            let filePath = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: filePath!)
        }
        
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]] else {return}
        
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        viewControllers = arrayM
    }

    /// 使用字典创建一个子控制器
    ///
    /// - parameter dict: 控制器信息字典[clsName, title, imageName]
    /// - return : 子控制器

    private func controller(dict: [String : AnyObject]) -> UIViewController   {
        //1.取得字典内容
       guard let clsName = dict["clsName"] as? String,
             let title = dict["title"] as? String,
             let imageName = dict["imageName"] as? String,
             let cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? BaseViewController.Type,
             let visitorDict = dict["visitorInfo"] as? [String: String]  else {
                return UIViewController()
        }
        //2.创建视图控制器
        let vc = cls.init()
        vc.title = title
        vc.visitorInfoDictionary = visitorDict
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .highlighted)
        //设置字体大小,默认大小是12号
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], for: .normal)

        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        //实例化导航控制器的时候,会调用push方法,将rootVC压栈
        let nav = NavigationController(rootViewController: vc)
        return nav
    }






}
